import React, { Fragment, useState } from 'react'
import { Button, Modal, Input, message, Typography } from 'antd';
import { post } from '../../../../../ajax/axios'
import { Api } from '../../../../../ajax/api'
import ReactNbsp from 'react-nbsp'

const { Paragraph } = Typography;

const UrlImageRecognition = function() {

  const [visible, setVisible] = useState(false)
  const [textValue, setTextValue] = useState('')
  const [wordsResult, setWordsResult] = useState<Array<any>>([])
  const [loading, setLoading] = useState(false)

  const okBtnClick = () => {
    if ( wordsResult.length > 0 ) {
      setWordsResult([])
      return
    }
    if (!textValue) {
      message.error('请输入数据')
      return
    }
    setLoading(true)
    post(Api.baidu.urlTextIdentify, {
      url: textValue
    }).then((data: any) => {
      setWordsResult(data.words_result)
      if (data.words_result.length === 0) {
        message.error('没有识别出文字')
      }
    }).catch(() => {}).finally(() => {
      setLoading(false)
    })
  }

  const textChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    setTextValue(event.target.value)
  }

  const cancelBtnClick = () => {
    setVisible(false)
  }

  const tests = wordsResult.map((text: any, index: number) => {
    return (
      <Paragraph key={ `texts-${index}` } copyable>{ text.words }</Paragraph>
    )
  })


  return (
    <Fragment>
      <Button size={ 'small' } type="primary" onClick={ () => setVisible(true) }>文字识别(图片链接)</Button>
      <ReactNbsp></ReactNbsp>
      <Modal
          title="文字识别(图片链接)"
          confirmLoading={loading}
          visible={visible}
          okText={ wordsResult.length > 0 ? '清除' : '识别' }
          onOk={okBtnClick}
          width={900}
          onCancel={cancelBtnClick}
        >
          {
            wordsResult.length > 0 ?
            tests
            :
            <Input.TextArea onChange={ textChange }></Input.TextArea>
          }
        </Modal>
    </Fragment>
  )
}

export default UrlImageRecognition